package com.ssy.lingxi.platform.manage.serviceimpl;

import cn.hutool.core.collection.CollectionUtil;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.platform.manage.api.model.dto.shop.ShopMemberInfoDTO;
import com.ssy.lingxi.platform.manage.constant.CommonBooleanEnum;
import com.ssy.lingxi.platform.manage.entity.base.QShopRule;
import com.ssy.lingxi.platform.manage.entity.base.QShopRuleDetail;
import com.ssy.lingxi.platform.manage.entity.base.Shop;
import com.ssy.lingxi.platform.manage.entity.base.ShopRuleDetail;
import com.ssy.lingxi.platform.manage.model.request.common.CommonIdRequest;
import com.ssy.lingxi.platform.manage.model.request.shop.ShopRuleDetailRequest;
import com.ssy.lingxi.platform.manage.repository.ShopRepository;
import com.ssy.lingxi.platform.manage.repository.ShopRuleDetailRepository;
import com.ssy.lingxi.platform.manage.service.IShopActivityService;
import com.ssy.lingxi.platform.manage.service.IShopRuleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wyx
 * @version 2.0.0
 * @menu 商城能力
 * @date 2021-09-26
 */
@Service
public class ShopActivityServiceImpl implements IShopActivityService {

    @Resource
    private JPAQueryFactory jpaQueryFactory;
    @Resource
    private ShopRuleDetailRepository shopRuleDetailRepository;
    @Resource
    private ShopRepository shopRepository;
    @Resource
    private IShopRuleService shopRuleService;

    /**
     * 获取自营商城详情
     */
    @Override
    public Wrapper<ShopRuleDetail> details(CommonIdRequest request) {
        return Wrapper.success(shopRuleDetailRepository.findById(request.getId()).orElse(null));
    }

    /**
     * 根据会员ID获取自营商城列表
     */
    @Override
    public Wrapper<List<ShopRuleDetail>> findListByMemberId(Long memberId) {
        if (memberId == null) {
            return Wrapper.fail("会员ID不能为空");
        }

        QShopRule qShopRule = QShopRule.shopRule;
        QShopRuleDetail qShopRuleDetail = QShopRuleDetail.shopRuleDetail;

        List<ShopRuleDetail> detailList = jpaQueryFactory.from(qShopRule)
                .select(qShopRuleDetail)
                .join(qShopRuleDetail).on(qShopRule.id.eq(qShopRuleDetail.shopRule.id))
                .where(qShopRule.memberId.eq(memberId))
                .where(qShopRuleDetail.state.eq(CommonBooleanEnum.YES.getCode()))
                .orderBy(qShopRuleDetail.shopId.asc())
                .fetch();

        if (CollectionUtil.isEmpty(detailList)) {
            return Wrapper.success(detailList);
        }

        List<Long> shopIdList = detailList.stream().map(ShopRuleDetail::getShopId).collect(Collectors.toList());
        List<Shop> shopList = shopRepository.findAllById(shopIdList);
        detailList = detailList.stream().peek(a ->
                shopList.stream().filter(b ->
                        b.getId().equals(a.getShopId())
                ).findFirst().ifPresent(shop -> a.setMemberOperate(shop.getMemberOperate()))
        ).collect(Collectors.toList());

        return Wrapper.success(detailList);
    }

    /**
     * 获取自营商城列表
     */
    @Override
    public Wrapper<List<ShopRuleDetail>> list(UserLoginCacheDTO sysUser) {
        QShopRule qShopRule = QShopRule.shopRule;
        QShopRuleDetail qShopRuleDetail = QShopRuleDetail.shopRuleDetail;

        List<ShopRuleDetail> detailList = jpaQueryFactory.from(qShopRule)
                .select(qShopRuleDetail)
                .join(qShopRuleDetail).on(qShopRule.id.eq(qShopRuleDetail.shopRule.id))
                .where(qShopRule.memberId.eq(sysUser.getMemberId()).and(qShopRule.memberRoleId.eq(sysUser.getMemberRoleId())))
                .where(qShopRuleDetail.state.eq(CommonBooleanEnum.YES.getCode()))
                .orderBy(qShopRuleDetail.shopId.asc())
                .fetch();
        return Wrapper.success(detailList);
    }

    /**
     * 设置默认自营商城
     *
     * @param id        商城明细id
     * @param isDefault 是否默认：0:否 1.是
     */
    @Override
    public Wrapper<Void> updateIsDefault(Long id, Integer isDefault) {
        ShopRuleDetail shopRuleDetail = shopRuleDetailRepository.findById(id).orElse(null);
        if (shopRuleDetail == null) {
            return Wrapper.fail(ResponseCode.MAN_RECORDS_DON_T_EXIST);
        }
        //设置默认值
        if (CommonBooleanEnum.YES.getCode().equals(isDefault)) {
            //商城表实体
            QShopRuleDetail qShopRuleDetail = QShopRuleDetail.shopRuleDetail;
            long count = jpaQueryFactory.from(qShopRuleDetail)
                    .where(qShopRuleDetail.shopRule.id.eq(shopRuleDetail.getShopRule().getId())
                            .and(qShopRuleDetail.environment.eq(shopRuleDetail.getEnvironment()))
                            .and(qShopRuleDetail.isDefault.eq(CommonBooleanEnum.YES.getCode())))
                    .fetchCount();
            if (count > 0) {
                return Wrapper.fail(ResponseCode.PLATFORM_MANAGE_MEMBER_ROLE_SHOP_DEFAULT_EXIST);
            }
        }
        shopRuleDetail.setIsDefault(isDefault);
        shopRuleDetailRepository.save(shopRuleDetail);
        return Wrapper.success();
    }

    /**
     * 修改自营商城配置信息
     */
    @Override
    public Wrapper<Void> update(ShopRuleDetailRequest shopRuleDetailRequest) {
        ShopRuleDetail shopRuleDetail = shopRuleDetailRepository.findById(shopRuleDetailRequest.getId()).orElse(null);
        if (shopRuleDetail == null) {
            return Wrapper.fail(ResponseCode.MAN_RECORDS_DON_T_EXIST);
        }
        shopRuleDetail.setName(shopRuleDetailRequest.getName());
        shopRuleDetail.setLogoUrl(shopRuleDetailRequest.getLogoUrl());
        shopRuleDetail.setDescribe(shopRuleDetailRequest.getDescribe());
        shopRuleDetailRepository.save(shopRuleDetail);
        //缓存到redis中
        shopRuleService.initToRedis();
        return Wrapper.success();
    }

    @Override
    public Wrapper<Boolean> existShop(ShopMemberInfoDTO dto) {
        QShopRule qShopRule = QShopRule.shopRule;
        QShopRuleDetail qShopRuleDetail = QShopRuleDetail.shopRuleDetail;
        List<ShopRuleDetail> detailList = jpaQueryFactory.from(qShopRule)
                .select(qShopRuleDetail)
                .join(qShopRuleDetail).on(qShopRule.id.eq(qShopRuleDetail.shopRule.id))
                .where(qShopRule.memberId.eq(dto.getMemberId()).and(qShopRule.memberRoleId.eq(dto.getMemberRoleId())))
                .where(qShopRuleDetail.state.eq(CommonBooleanEnum.YES.getCode()))
                .orderBy(qShopRuleDetail.shopId.asc())
                .limit(1)
                .fetch();
        return Wrapper.success(detailList.size() > 0);
    }
}
